package com.demo2do.fms.admin.handler.impl;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.fms.admin.dao.business.OtherFeeTypeDao;
import com.demo2do.fms.admin.dao.business.TransportCostDao;
import com.demo2do.fms.admin.entity.vam.Department;
import com.demo2do.fms.admin.entity.vam.UserStat;
import com.demo2do.fms.admin.entity.vam.VehicleCodeStat;
import com.demo2do.fms.admin.entity.vam.VehicleStatusStat;
import com.demo2do.fms.admin.handler.VamHandler;
import com.demo2do.fms.admin.rao.VamRao;
import com.demo2do.fms.entity.authority.Organization;
import com.demo2do.fms.entity.authority.User;
import com.demo2do.fms.entity.supplier.common.Supplier;
import com.demo2do.fms.entity.vehicle.tractor.Tractor;
import com.demo2do.fms.entity.vehicle.trailer.Trailer;

/**
 *
 * @author Ark
 *
 */
@Component("vamHandler")
public class VamHandlerImpl implements VamHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(VamHandlerImpl.class);

    @Value("#{config['vam.department.url']}")
    private String departmentUrl;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Dao
    private TransportCostDao transportCostDao;
    
    @Dao
    private OtherFeeTypeDao otherFeeTypeDao;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Rao
    private VamRao vamRao;
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.handler.VamHandler#listDepartment()
     */
    @SuppressWarnings("unchecked")
    public List<Department> listDepartment() {
        
        HttpResult httpResult = vamRao.listDepartment(departmentUrl, Collections.emptyMap());
        
        Map<String, Object> remoteData = JsonUtils.parse(httpResult.getResponseText());
        List<String> models = (List<String>) remoteData.get("models");
        List<Department> departments = JsonUtils.parseAsList(JsonUtils.toJson(models), Department.class);
        
        return departments;
        
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.handler.VamHandler#createUser(com.demo2do.fms.entity.authority.User)
     */
    public void create(User user) {
        
        try {
            
            // 构造用户信息
            Supplier supplier = genericDaoSupport.load(Supplier.class, user.getSupplierId());
            Organization organization = genericDaoSupport.load(Organization.class, supplier.getOrgId());
            
            UserStat userStat = new UserStat(user, organization);
            
            // 发送至消息队列
            String jsonString = JsonUtils.toJson(userStat);
            byte[] messageBody = jsonString.getBytes("UTF-8");

            Message message = MessageBuilder.withBody(messageBody)
                                            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                            .build();
            
            rabbitTemplate.setQueue("user-add");
            rabbitTemplate.convertAndSend("direct-fms", "user-add", message);
            
        } catch (Exception e) {
            logger.error("#create() - create user[id={}] error, exception=[{}]", user.getId(), e);
            throw BusinessException.newInstance("500", "VAM用户创建失败!" + e.getMessage());
        }
        
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.handler.VamHandler#edit(com.demo2do.fms.entity.authority.User)
     */
    public void edit(User user) {
    
        try {
            
            // 构造用户信息
            Supplier supplier = genericDaoSupport.load(Supplier.class, user.getSupplierId());
            Organization organization = genericDaoSupport.load(Organization.class, supplier.getOrgId());
            
            UserStat userStat = new UserStat(user, organization);

            // 发送至消息队列
            String jsonString = JsonUtils.toJson(userStat);
            byte[] messageBody = jsonString.getBytes("UTF-8");

            Message message = MessageBuilder.withBody(messageBody)
                                            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                            .build();
            
            rabbitTemplate.setQueue("user-edit");
            rabbitTemplate.convertAndSend("direct-fms", "user-edit", message);
            
        } catch (Exception e) {
            logger.error("#edit() - edit user[id={}] error, exception=[{}]", user.getId(), e);
            throw BusinessException.newInstance("500", "VAM用户操作失败!" + e.getMessage());
        }
        
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.handler.VamHandler#syncVehicleCode(com.demo2do.fms.entity.vehicle.Tractor, java.lang.String)
     */
    public void syncVehicleCode(Tractor tractor, String brandEnCode) {
        
        try {
            
            // 构造车辆信息
            VehicleCodeStat stat = new VehicleCodeStat(tractor, brandEnCode);
            
            // 发送至消息队列
            String jsonString = JsonUtils.toJson(stat);
            byte[] messageBody = jsonString.getBytes("UTF-8");

            Message message = MessageBuilder.withBody(messageBody)
                                            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                            .build();
            
            rabbitTemplate.setQueue("sync-vehicle-code");
            rabbitTemplate.convertAndSend("direct-fms", "sync-vehicle-code", message);
            
        } catch (Exception e) {
            logger.error("#syncVehicleCode() - edit tractor[id={}] error, exception=[{}]", tractor.getId(), e);
        }
        
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.handler.VamHandler#syncVehicleStatus(java.lang.String, com.demo2do.fms.entity.vehicle.Tractor, com.demo2do.fms.entity.vehicle.Trailer)
     */
    public void syncVehicleStatus(String type, Tractor tractor, Trailer trailer) {
        
        try {
            
            // 构建车辆审核状态信息
            VehicleStatusStat stat = null;
            if (StringUtils.equals("tractor", type)) {
                stat = new VehicleStatusStat(tractor);
            } else {
                stat = new VehicleStatusStat(trailer);
            }
            
            // 发送信息到消息队列
            String jsonString = JsonUtils.toJson(stat);
            byte[] messageBody = jsonString.getBytes("UTF-8");

            Message message = MessageBuilder.withBody(messageBody)
                                            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                            .build();
            
            rabbitTemplate.setQueue("sync-vehicle-status");
            rabbitTemplate.convertAndSend("direct-fms", "sync-vehicle-status", message);
            
        } catch (Exception e) {
            logger.error("#syncVehicleStatus() - occur exception=[{}]", e);
        }
        
    }

	/* (non-Javadoc)
	 * @see com.demo2do.fms.admin.handler.VamHandler#createAdmin(com.demo2do.fms.entity.authority.User)
	 */
	public void createAdminOrBranch(User user) {
        try {
            
            UserStat userStat = new UserStat();
            // 构建总部、分区数据
            userStat.buildAdminOrBranchData(user);
            
            // 发送至消息队列
            String jsonString = JsonUtils.toJson(userStat);
            byte[] messageBody = jsonString.getBytes("UTF-8");

            Message message = MessageBuilder.withBody(messageBody)
                                            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                            .build();
            
            rabbitTemplate.setQueue("user-add");
            rabbitTemplate.convertAndSend("direct-fms", "user-add", message);
            
        } catch (Exception e) {
            logger.error("#create() - create user[id={}] error, exception=[{}]", user.getId(), e);
            throw BusinessException.newInstance("500", "VAM用户创建失败!" + e.getMessage());
        }
	}

	/* (non-Javadoc)
	 * @see com.demo2do.fms.admin.handler.VamHandler#editAdmin(com.demo2do.fms.entity.authority.User)
	 */
	public void editAdminOrBranch(User user) {
        try {
            
            UserStat userStat = new UserStat();
            // 构建总部、分区数据
            
            userStat.buildAdminOrBranchData(user);

            // 发送至消息队列
            String jsonString = JsonUtils.toJson(userStat);
            byte[] messageBody = jsonString.getBytes("UTF-8");

            Message message = MessageBuilder.withBody(messageBody)
                                            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                                            .build();
            
            rabbitTemplate.setQueue("user-edit");
            rabbitTemplate.convertAndSend("direct-fms", "user-edit", message);
            
        } catch (Exception e) {
            logger.error("#edit() - edit user[id={}] error, exception=[{}]", user.getId(), e);
            throw BusinessException.newInstance("500", "VAM用户操作失败!" + e.getMessage());
        }
	}
    
}